<template>
	<el-card v-loading="loading" class="card" v-if="formList.length > 0">
		<div v-for="(item, index) in formList" :key="item.uuid">
			<div class="flex items-center mb-5">
				<el-tag size="large" type="primary">{{ `${title}${index + 1}` }}</el-tag>
				<el-icon v-if="props.hyArrayFormConfig.type !== 'view'" @click="() => add()" size="20" class="ml-3 cursor-pointer" color="#007fff"
					><CirclePlus
				/></el-icon>
				<el-icon
					v-if="index !== 0 && props.hyArrayFormConfig.type !== 'view'"
					class="cursor-pointer ml-5"
					size="20"
					color="red"
					@click="remove(item.uuid)"
					><CircleClose
				/></el-icon>
			</div>
			<HyForm
				:hyFormDefault="item.default"
				:hyFormConfig="hyArrayFormConfig"
				:hyFormFields="item.fields"
				:ref="($event:any) => setRef($event, item.uuid)"
				:showErrorMessage="false"
			/>
		</div>
	</el-card>
</template>
<script setup lang="ts">
import HyForm from '/@/components/HyForm/index.vue';

import { getUUId } from '/@/utils/hyFunc';
import type { FormInstance } from 'element-plus';
const props = defineProps({
	title: {
		type: String,
		default: '',
	},
	hyArrayFormConfig: {
		type: Object,
		default: () => ({
			labelWidth: '120px',
			span: 8,
			offset: 0,
			type: 'submit',
		}),
	},
	hyArrayFormFields: {
		type: Object,
		default: () => ({}),
	},
	hyArrayFormDefault: {
		type: Object,
		default: () => ({}),
	},
});
const { hyArrayFormFields, hyArrayFormDefault, hyArrayFormConfig } = toRefs(props);
//表单数据
const formList = ref<any>([]);
//新增
const add = (echoData?: any) => {
	setLoading();
	const uuid = getUUId();
	formList.value.push({
		uuid,
		fields: hyArrayFormFields,
		default: echoData || hyArrayFormDefault,
	});
};
//设置ref
const formRef: any = ref<FormInstance[]>([]);
const setRef = (e: any, uuid: any) => {
	if (e) {
		formRef.value[uuid] = e;
	}
};
//删除
const remove = (uuid: any) => {
	setLoading();
	formList.value = formList.value.filter((item: any) => item.uuid !== uuid);
	delete formRef.value[uuid];
};
//校验
const check = async () => {
	const names: string[] = Object.keys(formRef.value);
	const checkResult = await Promise.all(
		names.map((uuid: string) => {
			try {
				return formRef.value[uuid].check();
			} catch (error) {
				return false; // 假设出现异常则视为验证失败
			}
		})
	);
	// 如果所有表单的check方法都返回true，则isCheck为true
	const isCheck = !checkResult.some((item: boolean) => item === false);
	return isCheck;
};
//提交
const submit = () => {
	return Object.values(formRef.value).map((item: any) => item.hyForm);
};
//清除
const cancel = () => {
	formList.value = [];
	setTimeout(() => {
		formRef.value = [];
	}, 100);
};
//设置假loading
const loading = ref(false);
const setLoading = () => {
	loading.value = true;
	setTimeout(() => {
		loading.value = false;
	}, 300);
};
// 暴露
defineExpose({ add, submit, cancel, check, formList });
</script>
<style scoped lang="scss">
.card {
	:deep(.el-card__header) {
		padding: 5px 0;
	}
	:deep(.el-card__body) {
		padding: 20px 30px;
	}
}
</style>
